import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Request } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { OrderService } from './order.service';
import { CreateOrderDto } from './dto/create-order.dto';
import { UpdateOrderDto } from './dto/update-order.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
import { Role } from '../auth/enums/role.enum';

@ApiTags('订单')
@Controller('orders')
@UseGuards(JwtAuthGuard)
export class OrderController {
  constructor(private readonly orderService: OrderService) {}

  @Post()
  @ApiOperation({ summary: '创建订单' })
  @ApiResponse({ status: 201, description: '订单创建成功' })
  @ApiBearerAuth()
  create(@Body() createOrderDto: CreateOrderDto, @Request() req) {
    return this.orderService.create(createOrderDto, req.user.id);
  }

  @Get()
  @ApiOperation({ summary: '获取所有订单' })
  @ApiResponse({ status: 200, description: '返回所有订单' })
  @ApiBearerAuth()
  @Roles(Role.ADMIN)
  @UseGuards(RolesGuard)
  findAll() {
    return this.orderService.findAll();
  }

  @Get('my-orders')
  @ApiOperation({ summary: '获取当前用户的订单' })
  @ApiResponse({ status: 200, description: '返回当前用户的订单' })
  @ApiBearerAuth()
  findMyOrders(@Request() req) {
    return this.orderService.findAllByUser(req.user.id);
  }

  @Get(':id')
  @ApiOperation({ summary: '获取指定订单' })
  @ApiResponse({ status: 200, description: '返回指定订单' })
  @ApiBearerAuth()
  findOne(@Param('id') id: string, @Request() req) {
    // 管理员可以查看任何订单，普通用户只能查看自己的订单
    if (req.user.role === Role.ADMIN) {
      return this.orderService.findOne(id);
    } else {
      return this.orderService.findOne(id).then(order => {
        if (order.user_id !== req.user.id) {
          throw new Error('您无权查看此订单');
        }
        return order;
      });
    }
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新订单' })
  @ApiResponse({ status: 200, description: '订单更新成功' })
  @ApiBearerAuth()
  @Roles(Role.ADMIN)
  @UseGuards(RolesGuard)
  update(@Param('id') id: string, @Body() updateOrderDto: UpdateOrderDto) {
    return this.orderService.update(id, updateOrderDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除订单' })
  @ApiResponse({ status: 200, description: '订单删除成功' })
  @ApiBearerAuth()
  @Roles(Role.ADMIN)
  @UseGuards(RolesGuard)
  remove(@Param('id') id: string) {
    return this.orderService.remove(id);
  }

  @Post('sample')
  @ApiOperation({ summary: '添加示例订单' })
  @ApiResponse({ status: 201, description: '示例订单添加成功' })
  @ApiBearerAuth()
  addSampleOrders(@Request() req) {
    return this.orderService.addSampleOrders(req.user.id);
  }
}
